package com.guozcc.bootweb.platform.common;

import com.guozcc.bootweb.platform.config.exception.TradeException;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpUtils {
    private final static Logger log = LoggerFactory.getLogger(HttpUtils.class);

    /**
     * POST
     */
    public static String httpPost(String url,String sendMsg) throws TradeException {
        log.info("http post url = "+url);
        log.info("http post request msg = "+sendMsg);
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(url);
        StringEntity stringEntity = new StringEntity(sendMsg,"UTF-8");
        httpPost.setEntity(stringEntity);
        httpPost.setHeader("Content-type","application/json;charset=utf-8");
        try {
            CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
            StatusLine statusLine = httpResponse.getStatusLine();
            Header[] allHeaders = httpResponse.getAllHeaders();
            log.info("statusLine="+statusLine);
            HttpEntity entity = httpResponse.getEntity();
            String res = EntityUtils.toString(entity, "UTF-8");
            log.info("http post response = "+res);
            return res;
        }catch (Exception e){
            log.error("",e);
            throw new TradeException("1","http请求失败");
        }
    }

    /**
     * GET无参数请求
     */
    public static String httpGet(String url) throws TradeException {
        log.info("http get url = "+url);
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpGet httpGet = new HttpGet(url);
        try {
            CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity entity = httpResponse.getEntity();
            String res = EntityUtils.toString(entity, "UTF-8");
            log.info("http get response = "+res);
            return res;
        }catch (Exception e){
            log.error("",e);
            throw new TradeException("1","http请求失败");
        }
    }


//    public static void main(String[] args) throws TradeException {
//        String s = HttpUtils.httpGet("http://9.163.131.16:9999/WF");
//        System.out.println(s);
//
//        String s1 = HttpUtils.httpPost("http://9.163.131.244:3886/api/MBTS/MBTS/sendZCRW/KDYT", new JSONObject().fluentPut("abc","123").toJSONString());
//        System.out.println(s1);
//    }
}
